package com.histone.grab_ticket.aop;

import com.histone.grab_ticket.entity.ResultBean;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class ControllerAop {

    @Pointcut("execution(public com.histone.grab_ticket.entity.ResultBean *(..))")
    public void result() {
    }

    @Around("result()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        long startTime = System.currentTimeMillis();

        ResultBean<?> result;

        try {
            result = (ResultBean<?>) pjp.proceed();
        } catch (Throwable e) {
            // 处理异常
            result = handlerException(pjp, e);
        }

        log.info("{} use time: {}, result is {}" , pjp.getSignature(), (System.currentTimeMillis() - startTime), result.toString());

        return result;
    }

    private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {

        ResultBean<?> result;

        // 已知异常
        if (e instanceof NullPointerException) {
            result = new ResultBean<String>(ResultBean.ErrorCode.NULL, e.getMessage());
        } else {
            result = new ResultBean<String>(ResultBean.ErrorCode.ERROR, e.getMessage());
        }
        log.error(pjp.getSignature() + " error ", e.getMessage());

        return result;
    }
}
